/**
 * Simple Metrics Collector
 *
 * 轻量级本地指标收集器，专为本地MCP工具设计
 * 替换过度设计的企业级指标收集系统
 */

const { getLogger } = require('../logging/logger');

class SimpleMetricsCollector {
    constructor(configManager) {
        this.configManager = configManager;
        this.logger = getLogger('simple-metrics-collector');
        this.startTime = Date.now();

        // 基础计数器
        this.counters = {
            requests_total: 0,
            requests_success: 0,
            requests_failed: 0,
            requests_timeout: 0,
            mcp_calls_total: 0,
            mcp_calls_success: 0,
            mcp_calls_failed: 0
        };

        // 基础计时器
        this.timers = {
            total_response_time: 0,
            request_times: []
        };

        // 系统指标
        this.systemMetrics = {
            memory_usage: 0,
            cpu_usage: 0,
            uptime: 0
        };

        this.initialized = false;
        this.maxRequestTimes = 100; // 保留最近100个请求时间
    }

    /**
     * 初始化指标收集器
     */
    initialize() {
        if (this.initialized) {
            return;
        }

        this.logger.info('Simple Metrics Collector initialized');
        this.initialized = true;
    }

    /**
     * 增加计数器
     * @param {string} counter - 计数器名称
     * @param {number} value - 增加的值
     */
    incrementCounter(counter, value = 1) {
        if (this.counters.hasOwnProperty(counter)) {
            this.counters[counter] += value;
        } else {
            this.logger.warn(`Unknown counter: ${counter}`);
        }
    }

    /**
     * 记录请求开始
     * @returns {number} 请求开始时间
     */
    startRequest() {
        this.incrementCounter('requests_total');
        return Date.now();
    }

    /**
     * 记录请求结束
     * @param {number} startTime - 请求开始时间
     * @param {boolean} success - 是否成功
     * @param {boolean} timeout - 是否超时
     */
    endRequest(startTime, success = true, timeout = false) {
        const duration = Date.now() - startTime;

        // 更新计数器
        if (success && !timeout) {
            this.incrementCounter('requests_success');
        } else if (timeout) {
            this.incrementCounter('requests_timeout');
        } else {
            this.incrementCounter('requests_failed');
        }

        // 记录响应时间
        this.timers.total_response_time += duration;
        this.timers.request_times.push(duration);

        // 保持请求时间数组大小
        if (this.timers.request_times.length > this.maxRequestTimes) {
            this.timers.request_times.shift();
        }
    }

    /**
     * 记录MCP调用
     * @param {boolean} success - 是否成功
     */
    recordMcpCall(success = true) {
        this.incrementCounter('mcp_calls_total');
        if (success) {
            this.incrementCounter('mcp_calls_success');
        } else {
            this.incrementCounter('mcp_calls_failed');
        }
    }

    /**
     * 更新系统指标
     */
    updateSystemMetrics() {
        const memUsage = process.memoryUsage();

        this.systemMetrics = {
            memory_usage: memUsage.heapUsed,
            memory_total: memUsage.heapTotal,
            memory_external: memUsage.external,
            uptime: Date.now() - this.startTime
        };
    }

    /**
     * 获取当前指标
     * @returns {Object} 当前指标
     */
    getCurrentMetrics() {
        this.updateSystemMetrics();

        const metrics = {
            // 计数器
            ...this.counters,

            // 系统指标
            ...this.systemMetrics,

            // 计算指标
            error_rate: this.calculateErrorRate(),
            avg_response_time: this.calculateAvgResponseTime(),
            mcp_success_rate: this.calculateMcpSuccessRate(),

            // 时间戳
            timestamp: Date.now(),
            uptime_ms: this.systemMetrics.uptime
        };

        return metrics;
    }

    /**
     * 计算错误率
     * @returns {number} 错误率百分比
     */
    calculateErrorRate() {
        const total = this.counters.requests_total;
        if (total === 0) return 0;

        const failed = this.counters.requests_failed + this.counters.requests_timeout;
        return Math.round((failed / total) * 100 * 100) / 100; // 保留两位小数
    }

    /**
     * 计算平均响应时间
     * @returns {number} 平均响应时间
     */
    calculateAvgResponseTime() {
        const total = this.counters.requests_success + this.counters.requests_failed + this.counters.requests_timeout;
        if (total === 0) return 0;

        return Math.round(this.timers.total_response_time / total);
    }

    /**
     * 计算MCP成功率
     * @returns {number} MCP成功率百分比
     */
    calculateMcpSuccessRate() {
        const total = this.counters.mcp_calls_total;
        if (total === 0) return 0;

        return Math.round((this.counters.mcp_calls_success / total) * 100 * 100) / 100;
    }

    /**
     * 获取健康状态
     * @returns {Object} 健康状态
     */
    getHealthStatus() {
        const metrics = this.getCurrentMetrics();
        const issues = [];
        let status = 'healthy';

        // 检查错误率
        if (metrics.error_rate > 10) {
            status = 'critical';
            issues.push(`High error rate: ${metrics.error_rate}%`);
        } else if (metrics.error_rate > 5) {
            if (status === 'healthy') status = 'warning';
            issues.push(`Elevated error rate: ${metrics.error_rate}%`);
        }

        // 检查响应时间
        if (metrics.avg_response_time > 5000) {
            if (status === 'healthy' || status === 'warning') status = 'critical';
            issues.push(`High response time: ${metrics.avg_response_time}ms`);
        } else if (metrics.avg_response_time > 2000) {
            if (status === 'healthy') status = 'warning';
            issues.push(`Elevated response time: ${metrics.avg_response_time}ms`);
        }

        // 检查内存使用 (超过500MB为警告)
        const memoryMB = Math.round(metrics.memory_usage / 1024 / 1024);
        if (memoryMB > 800) {
            if (status === 'healthy' || status === 'warning') status = 'critical';
            issues.push(`High memory usage: ${memoryMB}MB`);
        } else if (memoryMB > 500) {
            if (status === 'healthy') status = 'warning';
            issues.push(`Elevated memory usage: ${memoryMB}MB`);
        }

        return {
            status,
            issues,
            metrics: {
                error_rate: metrics.error_rate,
                avg_response_time: metrics.avg_response_time,
                memory_usage_mb: memoryMB,
                uptime_minutes: Math.round(metrics.uptime_ms / 60000)
            },
            timestamp: new Date().toISOString()
        };
    }

    /**
     * 重置所有指标
     */
    reset() {
        // 重置计数器
        Object.keys(this.counters).forEach(key => {
            this.counters[key] = 0;
        });

        // 重置计时器
        this.timers.total_response_time = 0;
        this.timers.request_times = [];

        // 更新开始时间
        this.startTime = Date.now();

        this.logger.info('Metrics reset');
    }

    /**
     * 停止指标收集器
     */
    stop() {
        if (this.initialized) {
            this.logger.info(`Simple Metrics Collector stopped. Total requests: ${this.counters.requests_total}`);
            this.initialized = false;
        }
    }
}

module.exports = SimpleMetricsCollector;